import { cloneDeep, map, forEach } from "lodash";
import { basiclineOption, buildLineSeriesData } from '@/utils/chartOption';
import { formatChartTooltip, formatChartTooltipByData, formatUnit } from '@/utils/format';
/**
 * 网络数据-丢包数、重传数、srtt接口数据处理
 * @param data 后台数据
 * @param name 指标名称
 * @param unit 单位
 * @returns 折线图配置数据
 */
export const netLineOptionHandle = (data, name, unit) => {
  const options = cloneDeep(basiclineOption);
  if (!data?.length) {
    return options;
  }
  options.grid.top = 15;
  options.tooltip.confine = false;
  options.tooltip.appendToBody = true;
  options.xAxis[0].data = map(data, "time");
  options.yAxis[0].axisLabel.formatter = (v) => formatUnit(v, unit);
  options.series.push(buildLineSeriesData(name, map(data, "value")));
  options.tooltip.formatter = (params) => formatChartTooltip(params, unit);
  return options;
};

/**
 * 响应时间，错误率，请求量后台返回数据处理成折线图数据
 * @param data 后台数据
 * @param type rc-请求量 error-错误率 rt-响应时间
 * @returns 折现图配置数据
 */
export const lineOptionHandle = (data, type) => {
  const options = cloneDeep(basiclineOption);
  if (!data?.length) {
    return options;
  }
  options.xAxis[0].data = map(data[0].lineChartList, "time");
  options.legend.data = map(data, "url");
  options.tooltip.confine = false;
  options.tooltip.appendToBody = true;
  options.tooltip.enterable = true;
  if (type === "rc") {
    options.yAxis[0].axisLabel.formatter = (v) => formatUnit(v, "count");
    options.tooltip.formatter = (params) => formatChartTooltip(params, "count");
  } else if (type === "error") {
    options.yAxis[0].axisLabel.formatter = (v) => formatUnit(v, "%");
    options.tooltip.formatter = (params) =>
      formatChartTooltipByData(
        params,
        "%",
        data,
        "url",
        "lineChartList",
        "errorTotal",
        "个"
      );
  } else {
    options.yAxis[0].axisLabel.formatter = (v) => formatUnit(v, "ns");
    options.tooltip.formatter = (params) => formatChartTooltip(params, "ns");
  }
  if (type === "error") {
    forEach(data, (item) => {
      options.series.push(
        buildLineSeriesData(item.url, map(item.lineChartList, "errorRate"))
      );
    });
  } else {
    forEach(data, (item) => {
      options.series.push(
        buildLineSeriesData(item.url, map(item.lineChartList, "value"))
      );
    });
  }
  return options;
};
